package com.xxg.renrenorder.controller;

import com.xxg.renrencommon.domain.filedenum.orderenum.PaymentTypeEnum;
import com.xxg.renrencommon.domain.result.BaseResult;
import com.xxg.renrencommon.exception.ErrorMessage;
import com.xxg.renrencommon.exception.OrderManagerException;
import com.xxg.renrencommon.exception.exceptionenum.OrderExceptionCodeCodeEnum;
import com.xxg.renrenorder.domain.query.ModQuery;
import com.xxg.renrenorder.domain.query.OrderPayQuery;
import com.xxg.renrenorder.domain.query.OrderQuery;
import com.xxg.renrenorder.domain.result.ReFundResult;
import com.xxg.renrenorder.service.OrderService;
import com.xxg.renrenorder.service.PayService;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 支付controller
 *
 * @author xxg
 * @date 2020/11/18
 */
@Api(tags = "支付管理接口")
@RestController
@RequestMapping("/pay")
@AllArgsConstructor
public class PayController {
    private static final Logger logger = LoggerFactory.getLogger(PayController.class);
    private final PayService payService;
    private final OrderService orderService;

    @ApiOperation("订单支付-微信小程序")
    @RequestMapping(value = "lpWechatpayOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "orderPayQuery", value = "订单支付信息", required = true, dataType = "OrderPayQuery")})
    @ApiResponse(code = 200, message = "微信支付信息结果")
    public BaseResult<Map<String, String>> lpWechatpayOrder(@RequestBody @Validated OrderPayQuery orderPayQuery) {
        if (orderPayQuery.getOpenid() == null) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.INVALID_PARAMETER, ErrorMessage.OPENID_NOT_NULL,null);
        }
        return payService.wechatpayOrder(orderPayQuery.getId(), PaymentTypeEnum.LP_WECHATPAY.getValue(), orderPayQuery.getOpenid());
    }

    @ApiOperation("订单支付-模拟成功接口")
    @RequestMapping(value = "modPaySuccess", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "query", value = "mod信息", required = true, dataType = "ModQuery")})
    public BaseResult<Void> modPaySuccess(@RequestBody @Validated ModQuery query) {
        return payService.modPaySuccess(query);
    }

    @RequestMapping(value = "/lpWechatpayNotify", method = RequestMethod.POST)
    public String lpWechatpayNotify(HttpServletRequest request) {
        InputStream is = null;
        BufferedReader reader = null;
        String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        try {
            is = request.getInputStream();
            // 将InputStream转换成String
            reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            xmlBack = payService.lpWechatpayNotify(sb.toString());
        } catch (Exception e) {
            logger.error(ErrorMessage.WECHATPAY_NOTIFY_ERROR, e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return xmlBack;
    }

    @RequestMapping(value = "/lpWechatRefundNotify", method = RequestMethod.POST)
    public String lpWechatRefundNotify(HttpServletRequest request) {
        InputStream is = null;
        BufferedReader reader = null;
        String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
        try {
            is = request.getInputStream();
            // 将InputStream转换成String
            reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            xmlBack = payService.lpWechatRefundNotify(sb.toString());
        } catch (Exception e) {
            logger.error(ErrorMessage.WECHATPAY_NOTIFY_ERROR, e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return xmlBack;
    }

    @ApiOperation("执行退款")
    @RequestMapping(value = "reFund", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "orderQuery", value = "9售后订单ID", required = true, dataType = "com.dlrs.jz.ordermanager.domain.query.OrderQuery")})
    public BaseResult<Void> reFund(@RequestBody @Validated OrderQuery orderQuery) {
        ReFundResult response;
        try {
            response = payService.reFund(orderQuery.getId());
        } catch (OrderManagerException e) {
            return new BaseResult<>(e);
        }
        if (response != null) {
            return orderService.finishAfterSalesOrder(orderQuery.getId(), response);
        } else {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.CHECK_AFTER_SALES_STATUS);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("执行退款模拟接口")
    @RequestMapping(value = "reFundMock", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "orderQuery", value = "9售后订单ID", required = true, dataType = "com.dlrs.jz.ordermanager.domain.query.OrderQuery")})
    public BaseResult<Void> reFundMock(@RequestBody @Validated ModQuery orderQuery) {
        if (!orderQuery.checkPassword()) {
            return new BaseResult<>();
        }
        ReFundResult response;
        try {
            response = payService.reFundMock(orderQuery.getId());
        } catch (OrderManagerException e) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.REFUND_ERROR, e.getMessage(), null);
        }
        if (response != null) {
            return orderService.finishAfterSalesOrder(orderQuery.getId(), response);
        } else {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.CHECK_AFTER_SALES_STATUS);
        }
    }

}
